<template>
  <el-container class="box">
    <el-main >
      <el-row>

        <el-col :span="10" class="links-col left-card">
          <el-card style="height: 498px;border: none;" class="announcements">
            <template #header>
              <div class="card-header">
                <span>系统公告</span>
              </div>
            </template>
<!--            <ul class="infinite-list" style="overflow: auto;padding: 0;">-->


            <el-table style="" :data="notice"  height="400"  >
              <el-table-column type="expand">
                <template #default="props">
                  <div m="4">
                    <div style="width: 80%;margin: 0 auto" v-if="props.row.announcementContent">
                      <div ref="editorDiv" v-html="generateEditorContent(props.row.announcementContent)"></div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column fixed label="公告标题" prop="announcementTitle" />
              <el-table-column fixed label="发布时间" prop="announcementReleased" />
            </el-table>

<!--            </ul>-->
<!--            <ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto">-->
<!--              <li v-for="item in notice" :key="item.announcementId" class="infinite-list-item">{{ item.announcementTitle }}</li>-->
<!--            </ul>-->
          </el-card>
        </el-col>

        <el-col :span="14" class="attendance-col">
          <div class="attendance">
            <el-text size="large" tag="b">考勤</el-text>
            <el-button class="btn" type="primary" @click="getTime">{{btnText}}打卡</el-button>
          </div>
            <transition>
              <div>
                <div>
                  <div>
                    <el-calendar v-model="calendarValue">
                      <template #date-cell="{ data }">
                        <div class="date-cell">
                          <div class="calendar-day">
                            {{ data.day.split("-").slice(2).join("-") }}
                          </div>
                          <div
                            v-for="(item, index) in formatSchedule(data)"
                            :key="index"
                            class="calendarValue text-primary"
                          >
                          <template v-if="item.attendanceStatus==2">
                            <div class="text">
                              <span class="missing">旷工</span>
                            </div>
                          </template>
                          <template v-else-if="item.attendanceStatus==3">
                            <div class="text">
                              <span class="blue">请假</span>
                            </div>
                          </template>
                          <template v-else>
                            <div class="text">
                              <span :class="{'late': isLate(item.startHours, regular.regularStartHours), 'missing': !item.startHours}">上班：{{ item.startHours ||'缺卡' }}</span>
                            </div>
                            <div class="text">
                              <span :class="{'early-leave': isEarlyLeave(item.endHours, regular.regularEndHours), 'missing': !item.endHours}">下班：{{ item.endHours||'缺卡' }}</span>
                            </div>
                          </template>
                          </div>
                        </div>
                      </template>
                    </el-calendar>
                  </div>
                </div>
              </div>
                
            </transition>
        </el-col>

        <el-col :span="24" class="recommend-col bottom-card">
          <el-card style="border: none;">
            <template #header>
              <div class="card-header">
                <span>热门题目</span>
              </div>
            </template>

            <el-collapse @change="handleChange" style="overflow: auto;height: 230px;">
              <!-- 遍历 studentAndComment 数组生成多个 el-collapse-item -->
              <el-collapse-item v-for="(item, index) in studentAndComment" :key="index" :name="index + 1" :title="item.questionTitle + (item.questionsComments.length > 0?` (评论数：${item.questionsComments.length})` : '')">
                <div >
                  <!-- 遍历新的数组 studentComment，展示其 questionsComment 中的 commentContent -->
                  <div v-for="commentItem in studentComment" :key="commentItem.id">
                    <div v-if="commentItem.questionTitle === item.questionTitle">
                      <p style="margin-left: 5px">最新评论日期 :{{commentItem.questionsComments[0].createTime }}</p>
                      <p class="content-question" @click="showDialog(item)">
                        最新评论:{{ commentItem.questionsComments[0].commentContent }}
                        <span style="font-size: 14px; cursor: pointer">查看</span>
                      </p>
                    </div>
                  </div>
                </div>
                <div>
                  <!-- 遍历当前问题的所有学生，展示他们的头像 -->
                  <div v-for="student in item.students" :key="student.id">
                    <img class="studentImg" :src="student.avatar"/>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
          <!-- <div class="recommend-title">
            <el-text size="large" tag="b">题型</el-text>
            <a href="#" style="float: right;font-size: 14px;">更多</a>
          </div>
          <div class="recommend-items">
            <div>Java 中的包(package)用于什么目的?</div>
            <div>题型2</div>
          </div> -->
        </el-col>
      </el-row>
    </el-main>
    <el-dialog v-model="dialogVisible" title="查看评论" style="height: 70vh;overflow: auto;">
      <h1>题目：{{ currentQuestion.questionTitle }}</h1>

      <div class="post-card" v-if="loading">
        <div v-for="(item, index) in question_comments" :key="index" style="border-top: 1px solid #ebeef5; padding: 10px 0">
          <div style="display: flex; position: relative">
            <el-avatar :src="item.avatar" class="avatar"></el-avatar>
            <div class="post-info">
              <div class="username-level">
                <span class="username">{{ item.nickName }}</span>
                <span v-if="item.parentNickName">回复：{{ item.parentNickName }}</span>
              </div>
              <div class="post-time">{{ item.createTime }}</div>
            </div>
            <div class="delete-card" v-if="item.studentId == useStudentStore().studentInfo.studentId">
              <span></span>
              <el-dropdown>
                <span class="el-dropdown-link">
                  <i class="iconfont icon-a-13Ashenglve"></i>
                </span>
              </el-dropdown>
            </div>
          </div>
          <div class="post-content">
            <p :id="currentQuestion.commentContent === item.commentContent && currentQuestion.studentId === item.studentId ? 'currentComment' : ''">{{ item.commentContent }}</p>
          </div>
          <div style="display: flex; justify-content: flex-end;margin-bottom: 10px;">
<!--            <span style="font-size: 14px; cursor: pointer" @click="click_Reply(item)">回复</span>-->
            <span style="cursor: pointer; margin: 0 10px" v-if="item.isLike === 0">
              <i class="iconfont icon-dianzan1"></i>{{ item.likes }}
            </span>
            <span style="cursor: pointer; margin: 0 10px; color: blue" v-else>
              <i class="iconfont icon-dianzan"></i>{{ item.likes }}
            </span>
          </div>

<!--          <div class="reply" v-if="item.id == isReplyId">-->
<!--            <div class="chat-input-container">-->
<!--              <el-input v-model="replyContent" style="width: 100%" autosize resize="none" :rows="5" type="textarea" show-word-limit placeholder="请输入你的评论" ref="refInput"/>-->
<!--              <div style="display: flex;justify-content: flex-end; margin-top: 10px;">-->
<!--                <el-button type="primary" @click="submitComment">评论</el-button>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>

  
</template>
<script setup>
import {ref,reactive,computed, onMounted,nextTick} from 'vue';
import {ElMessage,ElMessageBox} from "element-plus";
import axios from '@/axios/index.js'
const value = ref(new Date());
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { useStudentStore } from "@/stores/student";
import { throttle } from "lodash";
// /*我的应用*/
// const routes = [
//   { path: '/personal/attendance', name: 'childRoute1', label: '考勤信息' },
//   { path: '/personal/info', name: 'childRoute2', label: '个人信息' },
//   { path: '/course', name: 'childRoute3', label: '我的课程' },
//   { path: '/questionBank', name: 'childRoute4', label: '开始刷题' },
//   { path: '/personal/errorQuestion', name: 'childRoute5', label: '我的错题' },
//   { path: '/exam', name: 'childRoute6', label: '开始考试' },
//   { path: '/personal/employmentInfo', name: 'childRoute6', label: '就业信息' },

// ];
// const getHref = (routeName) => {
//   const route = routes.find(route => route.name === routeName);
//   return route? route.path : '#';
// };

let student = ref({})
onMounted(() =>{
  student.value = JSON.parse(localStorage.getItem('student'));
  console.log(student.value);
  
})
// 年月日
function getData() {
  const date = new Date(); // 获取当前日期
  const year = date.getFullYear(); // 获取年份
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
  const day = String(date.getDate()).padStart(2, '0'); // 获取天数并补零
  const formattedDate = `${year}-${month}-${day}`; // 拼接成 YYYY-MM-DD 格式
  return formattedDate; // 返回日期字符串
}
// 时分秒
function getCurrentTime() {
  const date = new Date(); // 获取当前时间
  const hours = String(date.getHours()).padStart(2, '0'); // 获取小时并补零
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟并补零
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒数并补零
  const formattedTime = `${hours}:${minutes}:${seconds}`; // 拼接成 HH:mm:ss 格式
  return formattedTime; // 返回时间字符串
}

let btnText = ref("上班")
/*考勤打卡*/
const  getTime = async() => {
  if(!regularFlag.value) return ElMessage.error("未获取到打卡规则");
  let currentData = getData()

  let isFound = tradeData.schedule.some(element => {
    return element.attendanceDate == currentData && element.attendanceStatus == 3;
  });
  if(isFound) {
    btnText.value = "上班"
    return ElMessage.warning("请假不用打卡");
  }

  let data={
    studentId:student.value.studentInfo.studentId,
    classId:student.value.studentInfo.classId,
    regularId:regular.value.id,
    attendanceDate:currentData,
    startHours:"",
    endHours:"",
    attendanceStatus:0
  }
  tradeData.schedule.forEach(element => {
    if(element.attendanceDate==currentData){
      data.attendanceId = element.attendanceId
      if(element.startHours){
        data.endHours = getCurrentTime()
        // data.endHours = "22:21:00"
        element.startHours&&!(element.startHours > regular.value.regularStartHours) &&!(data.endHours < regular.value.regularEndHours)?data.attendanceStatus=1:data.attendanceStatus=0
      }else{
        data.startHours = getCurrentTime()
        if(data.startHours > regular.value.regularEndHours){ data.attendanceStatus = 0}
      }
    }
  });
    if(!data.startHours && !data.endHours){
      data.startHours = getCurrentTime()
      // data.startHours = "07:21:00"
    }

  
  ElMessageBox.confirm(
    `现在要${(data.endHours)?'更新下班':btnText.value}打卡吗?`,
    '提示',
    {
      confirmButtonText: '是的',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      request(data)
    })
}
const request = async (data) =>{
  let res= await axios.post("attendance/add",data);
  console.log(res);
  if(res.data.code==200){
    ElMessage.success("打卡成功");
    search()
  }
}

// const activeNames = ref(['1'])
const handleChange = (val) => {
  console.log(val)
}

const dataForm = ref([]);
const calendarValue = ref("");
const departmentName = ref([]);
const regular = ref({})
const tradeData = reactive({
  schedule: []
});
const text = ref("");
const listLoading = ref(false);
const id = ref("");

// 格式化日程，将返回的数据里的时间与日历控件里的时间匹配
const formatSchedule = computed(() => {
  return (data) => {
    return tradeData.schedule.filter((ele) => {
      let time = ele.attendanceDate;
      return time === data.day;
    });
  };
});


// 查询用户的打卡记录
const search = async () => {
  let res= await axios.get("attendance/selectStudentAttendance",);
  console.log(res);
  if(res.data.code==200){
    tradeData.schedule = res.data.data;
    tradeData.schedule.forEach(element => {
      if(element.attendanceDate==getData() && element.startHours){
        btnText.value = "下班"
      }
    })
  }
};
const regularFlag = ref(true)
// 查询用户的打卡规则
const searchRegular = async () => {
  let res= await axios.get("attendanceRegular/selectAttendanceRegular",{params:{
    status:1
  }});
  console.log(res);
  if(res.data.code==200 &&res.data.data){
    regular.value = res.data.data;
    regularFlag.value = true;
  }else{
    regularFlag.value = false;
    ElMessage.error("未获取到打卡规则");
  }
};
search()
searchRegular();
// 选择某一天的提示
// const chooseDay = (data) => {
//   // console.log(data);
  
//   if (data.result === "正常") {
//     ElMessage.success("该员工今日考勤一切正常");
//   } else {
//     ElMessage.warning("该员工今日存在" + data.result + "现象");
//   }
// };
// 迟到检查
const isLate = (startHours, regularStartHours) => {
  console.log(startHours,startHours && startHours > regularStartHours);
  
  return startHours && startHours > regularStartHours;
}
// 早退检查
const isEarlyLeave = (endHours, regularEndHours) => {
  return endHours && endHours < regularEndHours;
}
const count = ref(10)
// const load = () => {
//   count.value += 5
//   getSys()
// }
let notice =ref()
const getSys = async() =>{
  try {
    const res = await axios.get("/announcement/select",{
      params:{
        announcementStatus:1,
        current:1,
        size:count.value,
      }
    })
    console.log(res);
    if(res.data.code==200){
      notice.value = res.data.data.records
    }
  } catch (error) {
    console.log(error);
  }
}
function generateEditorContent(content) {
  return `<div ref="editorDiv"><Toolbar :editor="editorRef" :defaultConfig="defaultConfige" :mode="mode"/><Editor v-model="formData.announcementContent" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated">${content}</Editor></div>`;
}
getSys()

let studentAndComment =ref()
const getComment = async() =>{
  try {
    const res = await axios.get("/fquestion/selectStudentAndComment",)
    console.log(res.data.data);
    if(res.data.code==200){
      studentAndComment.value = res.data.data
    }
  } catch (error) {
    console.log(error);
  }
}
getComment()

let studentComment =ref()
const getStudentComment = async() =>{
  try {
    const res = await axios.get("/fquestion/selectStudentComment",)
    console.log(res.data.data);
    if(res.data.code==200){
      studentComment.value = res.data.data
    }

  } catch (error) {
    console.log(error);
  }
}
getStudentComment()

//要回复的评论对象
let replyComment = reactive({})
//是否回复id
let isReplyId = ref("");
//回复内容
let replyContent = ref();
let dialogVisible = ref(false);
//问题的所有评论
let question_comments = reactive([]);
//当前问题
let currentQuestion = ref();
//输入框聚焦
let refInput =ref()
//加载
let loading = ref(false);
/** 点击回复时*/
function click_Reply(item) {
  isReplyId.value = item.id;
  replyComment = item;
  replyContent.value = '';
  // 设置正在回复的评论 ID，用于显示回复框
  nextTick(() => {
    refInput.value[0].focus();
  })
}

// function submitComment() {
//   // 检查回复内容是否为空
//   if (!replyContent.value.trim()) {
//     ElMessage.warning('请输入评论内容');
//     return;
//   }
//   axios.post("/api/v1/front/questionsComment", {
//     studentId: useStudentStore().studentInfo.studentId,
//     questionId: replyComment.questionId,
//     commentContent: replyContent.value,
//     pid: replyComment.id
//   }, {
//     headers: {
//       "Content-Type": "application/json",
//     },
//   }).then(resp => {
//     ElMessage({
//       message: "评论成功",
//       type: 'success',
//     });
//     isReplyId.value = '-1';
//     replyContent.value = '';
//     // // 隐藏回复框
//     // isReplyTo = null;
//     // 添加以下代码以更新评论列表并关闭对话框
//     axios.get(`api/v1/front/questionsComment/showAllComments?questionId=` + replyComment.questionId).then((resp) => {
//       loading.value = true;
//       question_comments = resp.data.data;
//       // 更新小弹窗中的显示内容
//       if (question_comments.length > 0) {
//         // 假设 currentQuestion 中包含了最新评论的信息，可以根据实际情况调整
//         currentQuestion.value.latestComment = question_comments[0];
//       }
//     });
//     // 关闭对话框后重新获取数据
//     getComment();
//     getStudentComment();
//   });
// }

function showDialog(item) {
  loading.value = false;
  currentQuestion.value = item;
  axios.get(`api/v1/front/questionsComment/showAllComments?questionId=` + item.id).then((resp) => {
    loading.value = true;
    question_comments = resp.data.data;
  });
  dialogVisible.value = true;
}

// 新增变量用于跟踪正在回复的评论 ID
let isReplyTo = ref(null);

//防抖  限制500毫秒内只能点击一次
// const click_thumbs = throttle(thumbs,500)

/** 点赞逻辑 */
// function thumbs(item, index) {
//   axios.get("/api/v1/front/commentLike", {
//     params: {
//       studentId: useStudentStore().studentInfo.studentId,
//       commentId: item.id,
//       isLike: item.isLike,
//     },
//   })
//   .then((resp) => {
//     question_comments.value[index].likes = resp.data.data.likes;
//
//     if (item.isLike === 1) {
//       question_comments.value[index].isLike = 0;
//     } else {
//       question_comments.value[index].isLike = 1;
//     }
//   });
// }
</script>
<style scoped lang="less">
@import  "//at.alicdn.com/t/c/font_4465050_dpxzkk61j.css";
a{
  text-decoration: none;
}
li{
  list-style-type: none;
}

.box{
  margin: 30px auto;
  max-width: 96%;
}
/*右侧主体部分*/
.el-main {
  --el-main-padding: 10px 10px 0 20px;
  box-sizing: border-box;
  display: block;
  flex: 1;
  flex-basis: auto;
  overflow: auto;
  padding: var(--el-main-padding);
}

/*用户基本信息整体*/
.user-info-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #ebeef5;
  background-color: #fff;
}

/*用户头像*/
.user-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.user-details {
  text-align: center;
}

/*右侧中间整体样式*/
.links-col, .attendance-col, .recommend-col {
  padding: 0 10px 10px 10px;
  border: 1px solid #ebeef5;
  background-color: #fff;
}
.left-card,.bottom-card{
  padding: 0;
  height: 100%;
  .card-header{
    >span{
      font-size: 16px;
      font-weight: bold;
    }
  }
  .text{
    font-size: 14px;
  }
}

::v-deep .el-calendar-table thead th {
  border: 1px solid rgba(235, 238, 245);
  font-weight: 500;
  text-align: center;
}

// 取消右上角自带的按钮
::v-deep .el-calendar__header {
  .el-calendar__button-group {
    // display: none;
  }
}

// 只显示本月日期
::v-deep .el-calendar-table:not(.is-range) td.next {
  // display: none;
}
::v-deep .el-calendar-table:not(.is-range) td.prev {
  // visibility: hidden;
}

// 自定义文字居中显示
.calendarValue {
  text-align: center;
}
// 文本超出省略号显示
.text {
  width: 100%;
  // display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow:ellipsis;
}
.late {
  color: #df6e2c;
}
.early-leave {
  color: #df6e2c;
}
.missing {
  color: red;
}
.blue {
  color: rgb(39, 29, 222);
}
.text-primary {
  color: #8ad11c;
}

::v-deep .el-calendar-table .el-calendar-day {
    height: 65px;
}
::v-deep .el-calendar__body {
    padding: 10px 20px 3px;
}
.links-header, .attendance-header, .recommend-header {
  margin-bottom: 20px;
}

/*中间右侧*/
.attendance-col {
  border: 1px solid #ebeef5;
  background-color: #fff;
  /* 尝试设置一个固定高度 */
  height: 500px; /* 根据需要调整这个值 */
  overflow-y: auto; /* 允许垂直滚动 */
}

/*考勤日历*/
.attendance{
  margin: 15px;
  //border-bottom: 1px solid;
}

.attendance .btn{
  float: right;
}
::v-deep .el-calendar-table td.is-today {
    color: #fff;
    background: #1e80ff;
}
.infinite-list-item{
  font-size: 15px;
  font-weight: bold;
}
.studentImg{
  width: 30px;
  height: 30px;
  border-radius: 50%;
  float: right;
  margin-bottom: 5px;
  margin-top: 5px;
  margin-left: 10px;
}
.content-question {
  color: #999999;
  font-size: 15px;
  padding: 10px;
  width: 97%;
  background-color: #f7f8fc;
  display: flex;
  justify-content: space-between;
}
.reply {
  padding: 20px;
  background-color: #f7f8fc;
}
.post-time {
  font-size: 10px;
  color: #909399;
}

.post-content {
  margin-top: 10px;

  p {
    margin: 5px 0;
    font-size: 20px;
    padding-left: 80px;
  }
}

.iconfont{
  font-size: 18px;
}
.Comment{
  display: flex;
  justify-content: space-between;
}
.username-level {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  
}

.username {
  font-size: 16px;
  font-weight: bold;
  margin-right: 8px;
}

.avatar {
  display: flex;
  width: 40px;
  height: 40px;
  margin-right: 10px;
  margin-bottom: 16px;
}

.post-info {
  display: flex;
  flex-direction: column;
}



::-webkit-scrollbar
{
    width:6px;
    height: 10px;
    background-color:#dddee0;
}
</style>